package com.zb.activemq.have_two_try;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ScheduledMessage;

import javax.jms.*;

/**
 * Created by dongyuncong on 2017/8/9.
 */
public class Producer {

    static ConnectionFactory connectionFactory;


    static {
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://39.108.78.245:61616");


    }

    public static void main(String[] args) {

        for (int i = 0;i<500;i++){
            ProducerThread thread = new ProducerThread();
            new Thread(thread).start();
        }
    }

    static class ProducerThread implements Runnable {


        public void run() {
            Connection connection = null;
            try {
                connection = connectionFactory.createConnection();
                connection.start();
                Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
                Destination destination = session.createQueue("FirstQueue");
                MessageProducer producer = session.createProducer(destination);
                producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                sendMessage(session, producer);
                session.commit();
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                if (null != connection)
                    try {
                        connection.close();
                    } catch (Exception e) {
                        System.out.println(e);
                    }
            }

        }

        public void sendMessage(Session session, MessageProducer producer) throws Exception {
            TextMessage message = session.createTextMessage("ActiveMq: "+Thread.currentThread());
            long time = 60 * 1000;
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
            Thread.sleep(1000);
            producer.send(message);
        }
    }


}
